<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Visit\Action;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Call\Constants\ClientTypeCode;
use MoChat\App\Client\Contract\ClientContract;
use MoChat\App\Client\Model\Client;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 *
 * @Controller
 */
class VisitClient extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ClientContract
     */
    protected $clientService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     *
     * @RequestMapping(path="/dashboard/visit/client", methods="GET")
     */
    public function handle(): array
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        // 校验参数
        $params = $this->request->all();
        $count = Db::table('client')
            ->when(isset($params['employeeId']) && is_numeric($params['employeeId']), function ($query) use ($params) {
                $query->where('work_employee_id', $params['employeeId']);
            })
            ->when(isset($params['startTime']) && isset($params['endTime']) && !empty($params['startTime']) && !empty($params['endTime']), function ($query) use ($params) {
                $query->where('created_at', '>=', $params['startTime']);
                $query->where('created_at', '<', $params['endTime']);
            })
            ->count();
        $call = $this->callRecord($params);
        $rate=$count? (bcmul(bcdiv((string)$call, (string)$count, 6), "100", 2) . "%"):'0%';
        return ['clientCount' => $count, 'callCount' => $call, 'rate' =>$rate];

    }

    private function callRecord($data)
    {
        return Db::table('client as client')
            ->leftJoin('call_record as record', 'client.id', '=', 'record.client_id')
            ->when(isset($data['employeeId']) && is_numeric($data['employeeId']), function ($query) use ($data) {
                $query->where('client.work_employee_id', $data['employeeId']);
            })
            ->when(isset($data['startTime']) && isset($data['endTime']) && !empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                $query->where('client.created_at', '>=', $data['startTime']);
                $query->where('client.created_at', '<', $data['endTime']);
            })
            ->where('record.call_duration', '>', 0)
            ->where('record.call_type', '=', "out")
            ->count(Db::raw('DISTINCT mc_record.destination_number'));
    }
}
